﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace T11_TaskLongRunningAndCrossControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnLoginRunning_Click(object sender, EventArgs e)
        {
            Task task = new Task(() => 
            {
                Thread.Sleep(2000);
                Console.WriteLine($"Task子线程ID={Thread.CurrentThread.ManagedThreadId} {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
            },TaskCreationOptions.LongRunning);
            task.Start();

            task.Wait();
            Console.WriteLine($"主线程运行 tim={DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")}");
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Task task = new Task(() => 
            {
                this.label1.Text = "来自Task数据更新：正在学习Task多线程...";
            });
            task.Start(TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btn2_Click(object sender, EventArgs e)
        {
            Task task = new Task(() => 
            {
                Thread.Sleep(5000);//模拟耗时任务
                
                this.label1.Text = "来自Task数据更新：正在学习Task多线程，耗时任务观察......";
            });
            task.Start(TaskScheduler.FromCurrentSynchronizationContext());
        }

        private void btn3_Click(object sender, EventArgs e)
        {
            this.label1.Text = "数据更新中请耐心等待......";
            Task task = Task.Run(() => 
            {
                Thread.Sleep(5000);
            });

            task.ContinueWith((Task t1) => {
                this.label1.Text = "来自Task数据更新：正在学习Task多线程，耗时卡顿解决......";
            },TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
}
